import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;

public class demo {
    public static void main(String[] args) throws NoSuchFieldException {
        Student student = new Student();
        student.setName("heiman");
        student.setStudentNumber("201911111111");
        PlayStudent playStudent = copyP(student, PlayStudent.class);
        System.out.println(playStudent);
    }
    public static <T,F> F  copyP(T t1,Class<F> clazz){
        if(t1 == null || clazz == null){
            throw new IllegalArgumentException("输入的参数不能为空！");
        }
        try {
            // 创建需要copy的对象
            F f = clazz.getDeclaredConstructor().newInstance();

            // 获取 t1 和 f1 的所有字段
            Class<?> tClass = t1.getClass();
            Field[] t1Field = tClass.getDeclaredFields();

            Field[] f1Field = clazz.getDeclaredFields();
            for (Field field : t1Field) {
                // 设置访问私有字段
                field.setAccessible(true);

                for (Field f1 : f1Field) {
                    // 判断字段名称是否相同 并且 字段是否兼容
                    if(f1.getName().equals(field.getName()) && f1.getType().isAssignableFrom(field.getType())){
                        f1.setAccessible(true);
                        // 把t1中的值复制到 f1 中的 f对象中
                        f1.set(f, field.get(t1));
                    }
                }
            }

            return f;

        } catch (InvocationTargetException | NoSuchMethodException | IllegalAccessException | InstantiationException e) {
            throw new RuntimeException("复制对象失败！");
        }
    }
}
